package org.javaboy.custom_limit_demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class LimitFlowService {

    @Autowired
    StringRedisTemplate redisTemplate;

    public static final String KEY = "limit:flow";

    /**
     * 队列相当于我的令牌桶
     *
     * @return
     */
    public boolean isAllowed() {
        String s = redisTemplate.opsForList().rightPop(KEY);
        if (s == null) {
            // 队列为空，说明没有令牌了
            return false;
        }
        return true;
    }

    /**
     * 令牌的生产流程
     * 每隔3秒生产5个令牌，请求处理速率也是如此
     */
    @Scheduled(cron = "0/3 * * * * ?")
    public void produceToken() {
        ListOperations<String, String> ops = redisTemplate.opsForList();
        for (int i = 0; i < 5; i++) {
            Long size = ops.size(KEY);
            //意味着桶里边最多可以有 100 个令牌
            if (size < 100) {
                ops.leftPush(KEY, UUID.randomUUID().toString());
            }
        }
    }
}
